<?php
namespace app\modules\index\services;

use app\common\services\BaseService;
use app\utils\CoordinateUtil;

class DeliveryService extends BaseService{

    public static function calc($merchant_id,$lng_lat){
        $merchant = MerchantService::getInfoById($merchant_id);
        if(!$merchant){
            self::setError(\Yii::t("app","商户不存在"));
            return false;
        }
        if(empty($merchant['lng_lat'])){
            return [
                'distance'=>0,
                'delivery_price'=>0,
            ];
        }

        //平台配送
        $rules = \Yii::$app->params['delivery_rule'];
        if($merchant['delivery_type'] == "1" && !empty($merchant['delivery_rule'])){
            //商家配送
            $rules = $merchant['delivery_rule'];
        }
        $rules = explode(";",$rules);

        $lng_lat1= explode(",",$merchant['lng_lat']);
        $lng_lat2= explode(",",$lng_lat);
        $distance = CoordinateUtil::distance($lng_lat1[0],$lng_lat1[1],$lng_lat2[0],$lng_lat2[1]);
        $delivery_price = 0;
        $last = null;
        foreach($rules as $rule){
            $temp = explode("-",$rule);
            $last = $temp;
            if($distance <= $temp[0]){
                $delivery_price = $temp[1];
                break;
            }
        }
        if($delivery_price == 0){
            $delivery_price = $last[1];
        }

        return [
            'distance'=>$distance,
            'delivery_price'=>$delivery_price,
        ];
    }
}